package com.cyl.manager.pms.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.cyl.h5.domain.vo.ProductDetailVO;
import com.cyl.manager.pms.convert.ProductConvert;
import com.cyl.manager.pms.domain.entity.Product;
import com.cyl.manager.pms.domain.entity.Sku;
import com.cyl.manager.pms.domain.service.BrandDomainService;
import com.cyl.manager.pms.domain.service.ProductDomainService;
import com.cyl.manager.pms.domain.service.SkuDomainService;
import com.cyl.manager.pms.mapper.BrandMapper;
import com.cyl.manager.pms.mapper.ProductMapper;
import com.cyl.manager.pms.mapper.SkuMapper;
import com.cyl.manager.pms.req.ProductQueryReq;
import com.cyl.manager.pms.req.ProductReq;
import com.cyl.manager.pms.resp.ProductResp;
import com.github.pagehelper.PageHelper;
import com.sincere.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品信息Service业务层处理
 *
 *
 * @author zcc
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ProductService {

    private final SkuDomainService skuDomainService;

    private final ProductDomainService productDomainService;

    private final BrandDomainService brandDomainService;

    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    public ProductResp queryProductDetail(Long id) {
        Product product = productDomainService.getById(id);
        ProductResp productResp = ProductConvert.INSTANCE.entity2Resp(product);
        List<Sku> skus = skuDomainService.listByProductId(productResp.getId());
        productResp.setSkuList(skus);
        return productResp ;
    }

    /**
     * 查询商品信息列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 商品信息
     */
    public Page<ProductResp> queryProductByPage(ProductQueryReq query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        List<Product> list = productDomainService.listByPage(query, page);
        List<ProductResp> respList = ProductConvert.INSTANCE.entityList2RespList(list);
        return new PageImpl<>(respList, page, ((com.github.pagehelper.Page)list).getTotal());
    }

    /**
     * 导出查询
     * @param query
     * @return
     */
    public List<ProductResp> exportProductList(ProductQueryReq query) {
        List<Product> list = productDomainService.listByPage(query, null);
        return ProductConvert.INSTANCE.entityList2RespList(list);
    }

    /**
     * 查询所有商品
     * @return
     */
    public List<ProductResp> queryAllProduct() {
        List<Product> list = productDomainService.ListAllPage();
        return ProductConvert.INSTANCE.entityList2RespList(list);
    }

    /**
     * 新增商品信息
     *
     * @param req 商品信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean createProduct(ProductReq req) {

        Product product = ProductConvert.INSTANCE.req2Entity(req);
        product.setCreateTime(LocalDateTime.now());
        List<Sku> skuList = req.getSkuList();
        productDomainService.save(product);
        if(skuList!=null){
            skuList.forEach(sku -> {
                sku.setProductId(product.getId());
                sku.setCreateTime(LocalDateTime.now());
                skuDomainService.save(sku);
            });
        }
        return true;
    }

    /**
     * 修改商品信息
     *
     * @param req 商品信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ProductReq req) {
        Product dbProduct = productDomainService.getById(req.getId());
        List<Long> idList = req.getSkuList().stream().map(Sku::getId).filter(Objects::nonNull).collect(Collectors.toList());
        if (dbProduct == null) {
            return false;
        }
        Long userId = SecurityUtils.getUserId();
        Product product = ProductConvert.INSTANCE.req2Entity(req);
        List<Sku> skuList = req.getSkuList();
        product.setUpdateBy(userId);
        product.setUpdateTime(LocalDateTime.now());
        productDomainService.updateById(product);

        //查找库中所有的sku
        Map<Long, Sku> skuMap = skuDomainService.listByProductId(product.getId()).stream().collect(Collectors.toMap(Sku::getId, it -> it));

        //针对已有的进行编辑
        List<Sku> updateList = req.getSkuList().stream().filter(it -> it.getId() != null).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(updateList)) {
            log.info("共有{}个sku需要修改，{}，productId：{}",updateList.size(), JSONUtil.toJsonStr(updateList), req.getId());
            updateList.forEach(it->{
                Sku sku = skuMap.get(it.getId());
                sku.setUpdateBy(SecurityUtils.getUserId());
                sku.setUpdateTime(LocalDateTime.now());
                sku.setPrice(it.getPrice());
                sku.setSpData(it.getSpData());
                sku.setPic(it.getPic());
                sku.setOutSkuId(it.getOutSkuId());
                sku.setStock(it.getStock());
                skuDomainService.save(sku);
            });
        }
        //针对没有的进行新增
        List<Sku> addList = req.getSkuList().stream().filter(it -> it.getId() == null).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(addList)) {
            log.info("共有{}个sku需要新增，{}，productId：{}",addList.size(), JSONUtil.toJsonStr(addList), req.getId());
            addList.forEach(sku -> {
                sku.setProductId(product.getId());
                sku.setCreateTime(LocalDateTime.now());
                skuDomainService.save(sku);
            });
        }
        //删除
        List<Long> deleteIds = skuMap.keySet().stream().filter(it -> !idList.contains(it)).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(deleteIds)) {
            log.info("共有{}个sku需要删除，{}，productId：{}",deleteIds.size(), JSONUtil.toJsonStr(deleteIds), req.getId());
            List<Sku> deleteList = new ArrayList<>();
            deleteIds.forEach(deleteId ->{
                Sku skuFromDb = skuDomainService.getById(deleteId);
                skuFromDb.setDeleted(true);
                skuFromDb.setUpdateTime(LocalDateTime.now());
                skuFromDb.setUpdateBy(SecurityUtils.getUserId());
                deleteList.add(skuFromDb);
            });
            skuDomainService.updateBatchById(deleteList);
        }
        return true;
    }

    /**
     * 删除商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    public Boolean deleteById(Long id) {
        Product product = productDomainService.getById(id);
        product.setDeleted(true);
        product.setUpdateTime(LocalDateTime.now());
        product.setUpdateBy(SecurityUtils.getUserId());
        return productDomainService.updateById(product);
    }

    public ProductDetailVO queryDetail(Long id) {
        ProductDetailVO res = new ProductDetailVO();
        Product product = productDomainService.getById(id);
        res.setProduct(product);

        List<Sku> skus = skuDomainService.listByProductId(product.getId());
        res.setSkus(skus);

        if (product.getBrandId() != null) {
            res.setBrand(brandDomainService.getById(product.getBrandId()));
        }

        return res;
    }
}
